/*
 * @Author: jiu yin
 * @Date: 2023-04-27 14:23:19
 * @LastEditTime: 2023-12-15 17:30:32
 * @LastEditors: jiu yin zhen jing
 * @FilePath: \association-admin\src\view\adminUser\index.tsx
 * jiu
 */
import {
   Button,
   Form,
   Input,
   Modal,
   Select,
   Space,
   Switch,
   Table,
   message,
   theme
} from "antd";
import type { ColumnsType } from "antd/es/table";
import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import "./index.scss";

import {
   create_account,
   edit_account,
   edit_account_status,
   list_account,
   list_role,
   log_list,
} from "@/api/home";
import { getColorArr } from "@/utils";

import type { InputRef } from "antd";

import { butPermission } from "@/utils/auth";

function label(props) {
   let Permission = butPermission("bd");

   let [list_roleArr, setList_roleArr] = useState([] as any[]);

   useEffect(() => {
      list_role().then(res => {
         setList_roleArr(res.data.data);
      });
   }, []);

   const [form] = Form.useForm();
   let navigate = useNavigate();

   let getColorArrLen = getColorArr().length;

   interface DataType {
      user_id: number;
      username: string;
      phone: number;
      avatar: string;
      role_name: string;
      created_at: string;
      status: number;
   }
   const SwitchOnchange = (checked: boolean, item: any) => {
      console.log(`Switch checked: ${checked}`, item);
      statusStr2 = checked ? statusStr1 : statusStr;
      statusChange(item, checked);
   };

   const [disabled, setDisabled] = useState(false);

   const roleRef = useRef(null);
   let [roleType, setRoleType] = useState<string>("add");

   //表格

   const [datas, setDatas] = useState<DataType[]>([]);

   const [pagination, setPagination] = useState({
      current: 1,
      total: 0,
         pageSize: 11,
      hideOnSinglePage: true,
      keyword: "",
   });
   const [updataTable, setUpdataTable] = useState(true);
   useEffect(() => {
      list_account({
         page: pagination.current,
         limit: pagination.pageSize,
         keyword: pagination.keyword,
      }).then(res => {
         if (!res.data.data) res.data.data = [];
         res.data.data.forEach(item => {
            item.key = item.user_id;
         });
         setPagination({ ...pagination, total: res.data.total });
         setDatas([...res.data.data]);
      });
   }, [pagination.current, updataTable, pagination.keyword]);

   const handleTableChange = e => {
      setPagination({ ...pagination, current: e.current });
      // console.log(e);
   };

   const columns: ColumnsType<DataType> = [
      {
         title: "管理员名称",
         dataIndex: "username",
         render: text => <a>{text}</a>,
      },
      {
         title: "角色权限",
         dataIndex: "role_name",
      },
      {
         title: "备注",
         dataIndex: "remark",
      },
      {
         title: "创建时间",
         dataIndex: "created_at",
      },
      {
         title: "状态管理",
         key: "status",
         render: (_, item) => (
            <>
               <Switch
                  defaultChecked
                  disabled={!Permission}
                  checked={item.status}
                  onChange={checked => {
                     SwitchOnchange(checked, item);
                  }}
               />
            </>
         ),
      },

      {
         title: "状态",
         key: "status",
         render: (_, item) => (
            <>
               {item.status ? (
                  <p className="green">
                     <span className="dot greenBg"></span> 已开启
                  </p>
               ) : (
                  <p className="red">
                     <span className="dot redBg"></span> 已关闭
                  </p>
               )}
            </>
         ),
      },
      {
         title: "操作",
         key: "action",
         render: (_, item) => (
            <Space size="middle">
               {Permission && (
                  <a   onClick={() => operationlog(item)}>
                     操作日志
                  </a>
               )}

               {Permission && item.username !== "admin" && (
                  <a   onClick={() => edit(item)}>
                     编辑
                  </a>
               )}
            </Space>
         ),
      },
   ];
   let [itemUser, setUser] = useState({} as any);
   const operationlog = item => {
      setUser({ ...itemUser, ...item });
      log_list({ user_id: item.user_id }).then(res => {
         setSearchLog(res.data.data);
      });
      setIsLog(true);
   };

   //账号日志
   const [isLog, setIsLog] = useState(false);

   let [searchLog, setSearchLog] = useState([] as any[]);

   let searchInit = { keyword: "" };
   const [search, setSearch] = useState(searchInit);
   //日志搜索框input
   let [searchLogValue, setSearchLogValue] = useState("");
   const searchLogInput = (event: any) => {
      if (event.key === "Enter") {
         console.log(searchLogValue, "你要搜索吗");
         console.log( itemUser.user_id);

         // if (!searchLogValue) return message.error("请输入搜索内容");
         log_list({ user_id: itemUser.user_id, keyword: searchLogValue }).then(res => {
            setSearchLog(res.data.data);
         });
      }
   };

   //弹框
   const [isModalOpen, setIsModalOpen] = useState(false);

   //取消
   const cancel = () => {
      setIsModalOpen(false);
      form.resetFields();
      setDisabled(false);
      setformData(dataFormRoleInfo);
      setTags([]);
   };
   const [type, setType] = useState("");
   let dataFormRoleInfo = {
      username: "",
      password: "",
      role_id: "",
      remark: "",
      user_id: 0,
   };
   const [formData, setformData] = useState(dataFormRoleInfo);
   //重置表单
   useEffect(() => {
      form.setFieldsValue(formData);
   }, [formData]);
   //成功走得
   const onFinish = (values: any) => {
      console.log("Success:", values);
      console.log(type);
      // console.log(roleRef?.current?.getData());
      if (type == "add") {
         create_account({ ...values }).then(res => {
            message.success("创建角色成功");
            setIsModalOpen(false);
            setformData(dataFormRoleInfo);
            form.resetFields();
            setUpdataTable(!updataTable);
         });
      } else if (type == "edit") {
         edit_account({ ...values, user_id: formData.user_id }).then(res => {
            message.success("编辑角色成功");
            setIsModalOpen(false);
            setformData(dataFormRoleInfo);
            form.resetFields();
            setUpdataTable(!updataTable);
         });
      }
   };

   const edit = (item: any) => {
      console.log(item);
      setType("edit");
      setformData(item);
      setIsModalOpen(true);
   };
   const detail = item => {
      setDisabled(true);
      setformData(item);
      setIsModalOpen(true);
   };

   //失败走得
   const onFinishFailed = (errorInfo: any) => {
      console.log("Failed:", errorInfo);
      // setIsModalOpen(false);
   };

   //上传
   const onChangeUpload = e => {
      console.log(e, "上传");
      if (e.file.response?.code == 200) {
         console.log("上传成功");
      }
   };

   //穿梭框
   let [sourcesList, setSourcesList] = useState([
      {
         id: 1,
         label_name: "尼玛",
      },
      {
         id: 2,
         label_name: "阿斯达",
      },
      {
         id: 3,
         label_name: "打算",
      },
      {
         id: 4,
         label_name: "大多",
      },
      {
         id: 5,
         label_name: "阿斯达",
      },
      {
         id: 6,
         label_name: "得撒奥无",
      },
      {
         id: 7,
         label_name: "萨达",
      },
   ]);

   let [targetList, setTargetList] = useState([] as any[]);

   const setTargetListFn = (targetListObj: any) => {
      setTargetList(() => [...targetListObj]);
   };
   useEffect(() => {
      console.log(targetList, "targetList");
   }, [targetList]);

   //删除确认框
   const [modal, contextHolder] = Modal.useModal();

   //删除确认框
   const confirm = item => {
      modal.confirm({
         title: "删除",
         content: "是否将该条规则从列表中删除？",
         okText: "确认",
         cancelText: "取消",
         onOk() {
            // del_label({ label_id: item.label_id }).then(res => {
            //    message.success("删除成功");
            //    setUpdataTable(!updataTable);
            // });
         },
      });
   };

   let statusStr = (
      <p>
         是否将该条信息从<a  > 已开启 </a>状态变更为<a  > 已停用 </a>？
      </p>
   );
   let statusStr1 = (
      <p>
         是否将该条信息从<a  > 已停用 </a>状态变更为<a  > 已开启 </a>？
      </p>
   );
   let statusStr2 = <p></p>;

   //状态变更确认框
   const statusChange = async (item, checked) => {
      await new Promise(resolve => setTimeout(resolve, 0));
      modal.confirm({
         title: "状态变更",
         content: statusStr2,
         okText: "确认",
         cancelText: "取消",
         onOk() {
            edit_account_status({ user_id: item.user_id, status: checked ? 1 : 0 }).then(res => {
               message.success("修改状态成功");
               setUpdataTable(!updataTable);
            });
         },
      });
   };

   //角色编辑

   const { token } = theme.useToken();
   const [tags, setTags] = useState([] as string[]);
   const [inputVisible, setInputVisible] = useState(false);
   const [inputValue, setInputValue] = useState("");
   const inputRef = useRef<InputRef>(null);

   useEffect(() => {
      if (inputVisible) {
         inputRef.current?.focus();
      }
   }, [inputVisible]);

   return (
      <div className="intention adminUser">
         <div className="title">
            {Permission && (
               <Button
                  type="primary"
                  onClick={() => (
                     setIsModalOpen(true), setDisabled(false), setType("add"), setRoleType("edit")
                  )}>
                  + 新建账号
               </Button>
            )}

            {/* <div className='search'>
                    <Input placeholder="模糊搜索关键字" className='input' value={search.keyword} onChange={(e) => setSearch({ ...search, keyword: e.target.value })} />
                    <Button type="primary" className='ml_10' onClick={() => {
                        setPagination({ ...pagination, keyword: search.keyword })
                    }}>查询</Button>
                    <Button className='ml_10' onClick={() => { setSearch(searchInit), setUpdataTable(!updataTable) }}>重置</Button>
                </div> */}
         </div>
         <Table
            columns={columns}
            dataSource={datas}
            pagination={pagination}
            onChange={handleTableChange}
         />

         <Modal
            title={type == "add" ? "创建管理账号" : "编辑管理账号"}
            open={isModalOpen}
            onCancel={() => {
               cancel();
            }}
            keyboard
            footer={null}>
            <Form
               name="basic"
               labelCol={{ span: 12, offset: 10 }}
               wrapperCol={{ span: 100 }}
               style={{ maxWidth: 600, marginTop: "20px" }}
               initialValues={formData}
               onFinish={onFinish}
               onFinishFailed={onFinishFailed}
               autoComplete="off"
               form={form}
               layout="vertical">
               <div className="flex">
                  <Form.Item
                     label="用户名"
                     style={{ width: "168px" }}
                     rules={[
                        { required: true, message: "请输入用户名" },
                        {
                           validator: (_, value) => {
                              let reg = /^[0-9a-zA-Z]+$/;
                              return reg.test(value)
                                 ? Promise.resolve()
                                 : Promise.reject(new Error("请输入数字及英文字符"));
                           },
                        },
                     ]}
                     name="username">
                     <Input placeholder="不超过10字" maxLength={10} />
                  </Form.Item>
                  <Form.Item
                     label="备注"
                     style={{ width: "320px", marginLeft: "10px" }}
                     name="remark">
                     <Input placeholder="不超过30字" maxLength={30} />
                  </Form.Item>
               </div>

               <div className="flex">
                  <Form.Item
                     label="角色选择"
                     style={{ width: "168px" }}
                     rules={[{ required: true, message: "请选择角色" }]}
                     name="role_id">
                     <Select>
                        {list_roleArr.length > 0 &&
                           list_roleArr.map((item, index) => {
                              return (
                                 <Select.Option value={item.role_id} key={index}>
                                    {item.role_name}
                                 </Select.Option>
                              );
                           })}
                     </Select>
                  </Form.Item>
                  <Form.Item
                     label="密码设置"
                     style={{ width: "320px", marginLeft: "10px" }}
                     name="password"
                     rules={[
                        { required: true, message: "请输入密码" },
                        {
                           validator: (_, value) => {
                              let reg = /^[0-9a-zA-Z]+$/;

                              return reg.test(value)
                                 ? Promise.resolve()
                                 : Promise.reject(new Error("请输入数字及英文字符"));
                           },
                        },
                     ]}>
                     <Input.Password placeholder="数字及英文字符" />
                  </Form.Item>
               </div>

               <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                  <Button type="primary" htmlType="submit">
                     确定
                  </Button>
                  <Button
                     htmlType="button"
                     onClick={() => {
                        cancel();
                     }}
                     className="ml_10">
                     取消
                  </Button>
               </Form.Item>
            </Form>
         </Modal>

         <Modal
            title="账号日志"
            open={isLog}
            onCancel={() => {
               setIsLog(false);
            }}
            keyboard
            footer={null}>
            <div className="searchLog">
               <div className="searchLogInput">
                  <Input
                     placeholder="搜索日志 Enter键确认"
                     onKeyDown={e => {
                        searchLogInput(e);
                     }}
                     value={searchLogValue}
                     onInput={event => setSearchLogValue((event.target as HTMLInputElement).value)}
                  />
               </div>

               <div className="searchLogBody">
                  <ul>
                     {searchLog.length > 0 &&
                        searchLog.map((item, index) => {
                           return (
                              <li key={index}>
                                 <p>{item.created_at}</p>
                                 <p>{item.describe}</p>
                              </li>
                           );
                        })}
                  </ul>
               </div>
            </div>
         </Modal>

         {/* 删除确认对话框 */}
         {contextHolder}
      </div>
   );
}

export default label;
